package com.siyuanren.gcocp.service.impl;

import com.siyuanren.gcocp.base.BaseObject;
import com.siyuanren.gcocp.dto.ChapterDTO;
import com.siyuanren.gcocp.dto.WxCourseDTO;
import com.siyuanren.gcocp.dto.WxCourseTeaDTO;
import com.siyuanren.gcocp.entity.*;
import com.siyuanren.gcocp.enumm.CourseTeachType;
import com.siyuanren.gcocp.enumm.CourseType;
import com.siyuanren.gcocp.enumm.StatisticTypeEnum;
import com.siyuanren.gcocp.enumm.VideoTypeEnum;
import com.siyuanren.gcocp.enums.wx.CourseStateEnum;
import com.siyuanren.gcocp.mapper.MyWxChapterMapper;
import com.siyuanren.gcocp.mapper.MyWxCourseMapper;
import com.siyuanren.gcocp.mapper.base.WxCourseStatisticsMapper;
import com.siyuanren.gcocp.mapper.base.WxUserChapterMapper;
import com.siyuanren.gcocp.mapper.base.WxUserVideoProgressMapper;
import com.siyuanren.gcocp.service.ChapterService;
import com.siyuanren.gcocp.service.CourseService;
import com.siyuanren.gcocp.service.CourseStatisticsService;
import com.siyuanren.gcocp.service.VideoService;
import com.siyuanren.gcocp.util.DateUtil;
import com.siyuanren.gcocp.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


/**
 * Created by   anxing
 * Project_name gcocp-parent
 * Path         com.siyuanren.gcocp.service.impl
 * Date         2018/4/18
 * Time         14:26
 * Description
 */
@Slf4j
@Service
public class ChapterServiceImpl extends BaseObject implements ChapterService {
    @Autowired
    MyWxChapterMapper chapterMapper;
    @Autowired
    WxUserChapterMapper userChapterMapper;
    @Autowired
    MyWxCourseMapper myWxCourseMapper;
    @Autowired
    CourseService courseService;
    @Autowired
    private WxCourseStatisticsMapper courseStatisticsMapper;
    @Autowired
    private CourseStatisticsService courseStatisticsService;
    @Autowired
    private WxUserVideoProgressMapper userVideoProgressMapper;
    @Autowired
    private VideoService videoService;


    @Override
    public List<ChapterDTO> getChapterList(QueryChapterVO queryChapterVO) throws Exception {
        List<ChapterDTO> list = chapterMapper.getChapterList(queryChapterVO);
        QueryUserCourseStartVO userCourseStartVO = new QueryUserCourseStartVO();
        userCourseStartVO.setUserId(queryChapterVO.getUserId());
        userCourseStartVO.setCourseId(queryChapterVO.getCourseId());
        List<WxCourseStart> listStart = myWxCourseMapper.getUserCourseStart(userCourseStartVO);
        WxCourseTeaDTO course = courseService.getById(queryChapterVO.getCourseId());

        List<ChapterDTO> chapterList = new ArrayList<>();
        if (course.getTeachType().intValue() == CourseTeachType.FreeTeach.ordinal()) {
            // 自由学习模式, 展示所有章节
            chapterList.addAll(list);
        } else {
            // 引领式教学,每天学习一节
            if (listStart.size() > 0) {
                for (int i=0; i<list.size(); i++) {
                    ChapterDTO chapterDTO = list.get(i);
                    Date date = DateUtil.getDateAfter(listStart.get(0).getStartTime(), chapterDTO.getChapterNumber() -1);
                    setHour(5, date); // 每天凌晨5点更新
                    if (date.after(new Date())) {
                        continue;
                    } else {
                        chapterList.add(chapterDTO);
                    }
                    chapterDTO.setStartTimeStr(DateUtil.formatToSimpleDataString(date));
                }
            }
        }

//        // 初始化开始学习时间
//        if (listStart.size() > 0) {
//            int index = 0;
//            for (int i=chapterList.size()-1; i>=0; i--) {
//                ChapterDTO chapterDTO = chapterList.get(i);
//                Date date = DateUtil.getDateAfter(listStart.get(0).getStartTime(), index++);
//                chapterDTO.setStartTimeStr(DateUtil.formatToSimpleDataString(date));
//
//            }
//        }

        // 对于音视频章节, 设置音视频播放次数
        if (course.getCourseType() != CourseType.ChatCourse.getValue()) {
            for (ChapterDTO chapterDTO : chapterList) {
                chapterDTO.setChapterDetail(null);
                WxCourseStatistics cs = courseStatisticsService.getChapterPlayCount(chapterDTO.getId());
                if (cs != null) {
                    chapterDTO.setVideoPlayCount(cs.getCount());
                }
            }
        }
        return chapterList;
    }

    //设置小时
    private Date setHour(int hour, Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        return calendar.getTime();
    }

    @Override
    public List<Integer> getCourseClockList(QueryChapterVO queryChapterVO) throws Exception {
        return chapterMapper.getCourseClockList(queryChapterVO);
    }

    @Override
    @Transactional
    public void addCourseClock(ClockChapterVO clockChapterVO) throws Exception {
        WxUserChapter userChapter = new WxUserChapter();
        userChapter.setUserId(clockChapterVO.getUserId());
        userChapter.setCourseId(clockChapterVO.getCourseId());
        userChapter.setChapterId(clockChapterVO.getChapterId());
        insertOrUpdateUserChapter(userChapter);
    }

    @Override
    @Transactional
    public void submitChapterCourse(WxUserChapter userChapter) throws Exception {
        insertOrUpdateUserChapter(userChapter);
        updateCourseProgress(userChapter);

    }

    @Override
    public Integer getStudyProgress(Integer userId, Integer chapterId) {

        WxUserChapterExample exmple = new WxUserChapterExample();
        exmple.or().andUserIdEqualTo(userId).andChapterIdEqualTo(chapterId)
        .andAvailableEqualTo(true);
        List<WxUserChapter> wxUserChapters = userChapterMapper.selectByExample(exmple);
        if (wxUserChapters.isEmpty()) {
            return 0;
        } else {
            return wxUserChapters.get(0).getLastContentId();
        }
    }

    @Override
    @Transactional
    public void addPlayCount(AddPlayCountVO addPlayCountVO) {
        WxCourseStatistics courseStati = courseStatisticsService.getChapterPlayCount(addPlayCountVO.getChapterId());
        if (courseStati == null) {
            courseStati = new WxCourseStatistics();
            courseStati.setCount(1);
            courseStati.setType(StatisticTypeEnum.ChapterStati.ordinal());
            courseStati.setGoalId(addPlayCountVO.getChapterId());
            courseStatisticsMapper.insertSelective(courseStati);
        } else {
            courseStati.setCount(courseStati.getCount() + 1);
            courseStatisticsMapper.updateByPrimaryKeySelective(courseStati);
        }
    }

    @Override
    public ChapterDTO getChapterDetail(QueryChapterDetailVO chapterDetailVO) throws Exception {
        List<ChapterDTO> ll = chapterMapper.getChapterDetail(chapterDetailVO);
        if (ll.isEmpty()) {
            return null;
        }
        ChapterDTO dto = ll.get(0);
        QueryUserCourseStartVO userCourseStartVO = new QueryUserCourseStartVO();
        userCourseStartVO.setUserId(chapterDetailVO.getUserId());
        userCourseStartVO.setCourseId(chapterDetailVO.getCourseId());
        List<WxCourseStart> listStart = myWxCourseMapper.getUserCourseStart(userCourseStartVO);
        WxCourseTeaDTO course = courseService.getById(chapterDetailVO.getCourseId());

        // 初始化开始学习时间
        if (listStart.size() > 0) {
            Date date = DateUtil.getDateAfter(listStart.get(0).getStartTime(), dto.getChapterNumber() -1);
            dto.setStartTimeStr(DateUtil.formatToSimpleDataString(date));
        }

        // 对于音视频章节, 设置音视频播放次数
        if (course.getCourseType() != CourseType.ChatCourse.getValue()) {
            WxCourseStatistics cs = courseStatisticsService.getChapterPlayCount(dto.getId());
            if (cs != null) {
                dto.setVideoPlayCount(cs.getCount());
            }
            // 设置观看进度
            setVideoProgress(chapterDetailVO.getUserId(), dto);

            // 如果是音频课程, 设置音频mp3地址
            if (dto.getVideoType() == VideoTypeEnum.Audio.getValue()) {
                String audioUrl = videoService.getAudioUrl(dto.getVideoUuid());
                dto.setAudioUrl(audioUrl);
            } else {
                String videoUrl = videoService.getVideoUrl(dto.getVideoUuid());
                dto.setAudioUrl(videoUrl);
            }
        }
        return dto;
    }

    private void setVideoProgress(Integer userId, ChapterDTO chapterDTO) {
        WxUserVideoProgressExample example = new WxUserVideoProgressExample();
        example.or().andUuidEqualTo(chapterDTO.getVideoUuid()).andUserIdEqualTo(userId);
        List<WxUserVideoProgress> list = userVideoProgressMapper.selectByExample(example);
        if (list.size() > 0) {
            chapterDTO.setPosition(list.get(0).getPosition());
        }
    }

    @Override
    @Transactional
    public void submitVideoProgress(VideoProgoressVO vo) {
        WxUserVideoProgressExample example = new WxUserVideoProgressExample();
        example.or().andUserIdEqualTo(vo.getUserId()).andUuidEqualTo(vo.getUuid());
        List<WxUserVideoProgress> wxUserVideoProgresses = userVideoProgressMapper.selectByExample(example);
        WxUserVideoProgress vp = new WxUserVideoProgress();
        vp.setUserId(vo.getUserId());
        vp.setDuration(vo.getDuration());
        vp.setPosition(vo.getPosition());
        vp.setUuid(vo.getUuid());
        if (wxUserVideoProgresses.isEmpty()) {
            userVideoProgressMapper.insertSelective(vp);
        } else {
            vp.setDuration(wxUserVideoProgresses.get(0).getDuration() + vo.getDuration());
            vp.setId(wxUserVideoProgresses.get(0).getId());
            userVideoProgressMapper.updateByPrimaryKeySelective(vp);
        }
    }

    /**
     * 更新课程进度
     * @param userChapter
     * @throws Exception
     */
    private void updateCourseProgress(WxUserChapter userChapter) throws Exception {
        // 更新课程进度
        QueryChapterVO queryChapterVO = new QueryChapterVO();
        queryChapterVO.setCourseId(userChapter.getCourseId());
        queryChapterVO.setUserId(userChapter.getUserId());
        List<ChapterDTO> list = chapterMapper.getChapterList(queryChapterVO);
        boolean complete = true;
        for (ChapterDTO chapterDTO : list) {
            if (!chapterDTO.isHomeworkComplete()) {
                complete = false;
                break;
            }
        }
        if (complete) {
            WxUserCourse userCourse = new WxUserCourse();
            userCourse.setId(userChapter.getCourseId());
            userCourse.setGradTime(new Date());
            courseService.submitCourseProgress(userCourse);
        }
    }

    private void insertOrUpdateUserChapter(WxUserChapter userChapter) {
        WxUserChapterExample example = new WxUserChapterExample();
        example.or().andChapterIdEqualTo(userChapter.getChapterId()).andUserIdEqualTo(userChapter.getUserId());

        if (userChapterMapper.countByExample(example) == 0) {
            userChapter.setCreateTime(new Date());
            userChapterMapper.insertSelective(userChapter);
        } else {
            userChapterMapper.updateByExampleSelective(userChapter, example);
        }
    }
}
